<?php

require '../vendor/autoload.php';

use Gnway\Util\Concurrent\Executors;
use Gnway\Util\Concurrent\Process;
use Gnway\Util\Concurrent\Runnable;
use Gnway\Util\Concurrent\WaitException;

$pool = Executors::newFixedPool(2);
for ($i = 0; $i < 10; $i++) {
  $task = new class($i) implements Runnable {
    private int $id;

    public function __construct(int $id)
    {
      $this->id = $id;
    }

    public function run(): void
    {
      $now = time();
      while (time() - $now < 30 && !Process::currentProcess()->isInterrupted()) {
        echo '[' . $this->id . ']' . date('H:i:s') . ', pid: ' . getmypid() . PHP_EOL;
        sleep(1);
      }
    }
  };
  $pool->submit($task);
}
$pool->start();

try {
  $pool->wait(5);
} catch (WaitException $ex) {
  echo 'Wait timeout: ' . $ex->getMessage() . PHP_EOL;
  $pool->shutdown();
}

echo 'Shutdown success!', PHP_EOL;

exit(0);